<template>
    <div>
        <el-form-item :prop="item.name || ''" :label="item.label" v-bind="item.formItemProps || {}" ref="el-form-item">
            <div :class="{fullscreen:fullscreen}" class="tinymce-container editor-container">
                <textarea :id="tinymceId" class="tinymce-textarea"/>
            </div>
        </el-form-item>
    </div>
    
</template>

<script>
import plugins from "./plugins";
import toolbar from "./toolbar";
import {server_request } from "../../../utils/request";
import { objectAssign } from "../../../utils/common";
import { doUpload} from "../../../utils/upload/utils";
import uploadConfig from "../../../config/upload";

/*
    安装：
    需要将 /PopoForm/components/tinymce/tinymce5.4.0 目录，拷贝到代码根目录下的 public 目录中
    并在index.html 和 index-dev.html 中引用该目录中的脚本，例如：
    <script src="/tinymce5.4.0/tinymce.min.js">< /script>

*/
export default {
    name: "PopoTinymce",
    props: {
        id: {
            type: String,
            default: function() {
                return ("vue-tinymce-" + +new Date() + ((Math.random() * 1000).toFixed(0) + ""));
            }
        },
        value: {
            type: String,
            default: ""
        },
        item: {type: Object },
    },
    data() {
        return {
            mvalue: this.value,
            hasChange: false,
            hasInit: false,
            tinymceId: this.id,
            fullscreen: false,

            height: 500,
            toolbar: toolbar,
            menubar: "file edit insert view format table",

            /*
                文件上传使用的方式，支持
                server 服务器
                oss 阿里云OSS
                bos 百度云bos
                cos 腾讯云cos
                qiniu 七牛
             */
            fileUploadTarget: "server",
        };
    },
    computed: {},
    watch: {
        value(val) {
            if (!this.hasChange && this.hasInit) {
                this.$nextTick(()=> {
                    window.tinymce.get(this.tinymceId).setContent(val || "")
                });
            }
        },
        mvalue(val) {
            this.$emit("input", val);
        },
    },
    created(){
        // console.log( "input", uploadConfig);
        var opt = objectAssign( {}, this.item.props);
        this.opt = opt;
        this.height = this.item.height ? this.item.height : this.height;
        this.toolbar = this.item.toolbar ? this.item.toolbar : this.toolbar;
        this.menubar = this.item.menubar ? this.item.menubar : this.menubar;
    },
    mounted() {
        this.initTinymce();
        // setTimeout( ()=>{
        //     let notification = tinymce.activeEditor.notificationManager.open({
        //         text: ' 测试一个进度条',
        //         progressBar: true,
        //         icon: "upload",
        //         type: "info",
        //         closeButton: false,
        //         timeout: 864000000,
        //     });
        // }, 1000);
    },
    activated() {
        this.initTinymce();
    },
    deactivated() {
        this.destroyTinymce();
    },
    destroyed() {
        this.destroyTinymce();
    },
    methods: {
        initTinymce() {
            const _this = this;
            window.tinymce.init({
                language: "zh_CN",
                selector: `#${this.tinymceId}`,
                height: this.height,
                body_class: "panel-body ",
                object_resizing: false,
                toolbar: this.toolbar.length > 0 ? this.toolbar: toolbar,
                menubar: this.menubar,
                plugins: plugins,
                end_container_on_empty_block: true,
                code_dialog_height: 450,
                code_dialog_width: 600,
                advlist_bullet_styles: "square",
                advlist_number_styles: "default",
                imagetools_cors_hosts: uploadConfig.tinymce_imagetools_cors_hosts || [],
                default_link_target: "_blank",
                link_title: false,
                nonbreaking_force_tab: true,
                branding: false,
                font_formats: '宋体=SimSun;黑体=SimHei;微软雅黑=Microsoft YaHei;仿宋=FangSong;楷体=KaiTi;Arial=Microsoft YaHei,arial,helvetica,sans-serif; Courier New=courier new,courier,monospace; AkrutiKndPadmini=Akpdmi-n',
                fontsize_formats: "8pt 10pt 12pt 14pt 18pt 24pt 36pt 48px",
                powerpaste_word_import: "prompt",
                powerpaste_html_import: "prompt",
                // automatic_uploads: true,
                images_reuse_filename: true,

                init_instance_callback: editor =>{
                    if (_this.value) {
                        editor.setContent(_this.value);
                    }
                    _this.hasInit = true;
                    editor.on("NodeChange Change KeyUp SetContent", () =>{
                        this.hasChange = true;
                        this.mvalue = editor.getContent();
                    });
                },
                setup(editor) {
                    editor.on("FullscreenStateChanged", e =>{
                        _this.fullscreen = e.state;
                    });
                },
                // images_upload_handler 只能执行图片的上传，碰到链接文件、多媒体就没用了。 
                file_picker_callback: function(callback, value, meta) {
                    console.log( "meta value", value);
                    console.log( "meta", meta);
                    let filetype = "";

                    switch(meta.filetype){
                        case 'image':
                            filetype='image/*';
                            break;
                        case 'media':
                            filetype = 'audio/*,video/*';
                            break;
                        case 'file':
                        default:
                    }

                    var input = document.createElement('input');
                        input.setAttribute('type', 'file');
                        input.setAttribute('accept', filetype);
                    input.onchange = function() {
                        var file = this.files[0];
                        // _this.$message( "上传中...");
                        var notification = _this.createProgressBar();
                        _this.todoUpload( 
                            file, 
                            (percent)=>{
                                if( percent < 100){
                                    notification.progressBar.value( percent);
                                }else{
                                    tinymce.activeEditor.notificationManager.close();
                                }
                            }, 
                            ( url)=>{
                                tinymce.activeEditor.notificationManager.close();
                                // _this.$message.close();
                                callback( url);
                            }, 
                            (e) => {
                                tinymce.activeEditor.notificationManager.close();
                                _this.$message.error( "上传失败");
                                console.error( "上传失败(Tinymce.file_picker_callback)", e);
                            }
                        );
                    }
                    input.click();
                },
                images_upload_handler(blobInfo, success, failure, progress) {
                    let file = blobInfo.blob();
                    console.log( "file", file);

                    if( !file.name){
                        file.name = blobInfo.filename();
                    }

                    _this.todoUpload( file, progress, success, failure);
                }
            });
        },
        createProgressBar: function (){
            let notification = tinymce.activeEditor.notificationManager.open({
                text: '　上传进度',
                progressBar: true,
                icon: "upload",
                type: "info",
                closeButton: false,
                timeout: 864000000,
            });
            // console.log( notification);

            return notification;
        },
        todoUpload( file, progress, success, failure){
            let ext = file.name.substr( file.name.lastIndexOf(".") );
            let fileOnlinePath = [
                Date.now().toString(36),
                Math.random().toString( 36).substr( 2, 8)
            ];

            if( ext.length > 1){
                fileOnlinePath.push( ext);
            }

            fileOnlinePath = "/tinymce/upload/" + fileOnlinePath.join( "_");

            doUpload( 
                file,
                {
                    fileOnlinePath: fileOnlinePath,
                    progress: (e) => {progress( Math.round( e.percent)); },
                    success: (e) => { success( e.data);},
                    failure: ( e) => { failure( "上传失败");},
                }
            );
        },
        destroyTinymce() {
            if (window.tinymce.get(this.tinymceId)) {
                window.tinymce.get(this.tinymceId).destroy();
            }
        },
        setContent(value) {
            window.tinymce.get(this.tinymceId).setContent(value);
        },
        getContent() {
            window.tinymce.get(this.tinymceId).getContent();
        },
    }
};
</script>

<style>
  .tox-notifications-container{
    z-index: 1201;
  }
  .tox :not(svg):not(rect).tox-notifications-container{
    /*background-color: #fff;*/
  }
</style>

<style scoped>
  .tinymce-container {
    position: relative;
  }
  .tinymce-container >>> .mce-fullscreen {
    z-index: 10000;
  }
  .tinymce-textarea {
    visibility: hidden;
    z-index: -1;
  }
  .editor-custom-btn-container {
    position: absolute;
    right: 4px;
    top: 4px;
    /*z-index: 2005;*/
  }
  .fullscreen .editor-custom-btn-container {
    z-index: 10000;
    position: fixed;
  }
  .editor-upload-btn {
    display: inline-block;
  }
</style>
